/**
  * @Description: 艺术品信息
  *
  * @Author MING
  * @Email  lmm_work@163.com
  * @Date   2019/1/22 15:13
　*/

layui.define(['table', 'form','upload','laytpl'], function(exports){
    var $ = layui.$,
        table = layui.table,
        form = layui.form,
        admin = layui.admin,
        configs = layui.configs,
        upload = layui.upload,
        laytpl= layui.laytpl;

    //艺术品信息显示
    table.render({
        elem: '#lay-tab'
        ,url: configs.base_server +'/art/artInfo/list'
        ,toolbar: true
        ,cols: [[
            {type: 'checkbox'}
            ,{field: 'artInfo', width: 150, title: '艺术品数字身份证', templet: '<div>{{d.artInfo.icdn}}</div>'}
            ,{field: 'artInfo', title: '艺术品名称', minWidth: 80, width: 100,templet: '<div>{{d.artInfo.artName}}</div>'}
            ,{field: 'artType', title: '类别', minWidth: 60, width: 100,templet: '<div>{{d.artType.artTypeName}}</div>'}
            ,{field: 'artImage', title: '艺术品图片',width: 150,templet:'<div><img src="{{d.artImage.coverImageUrl}}"></div>'}
            ,{title: '当前状态',toolbar: '#art-status', minWidth: 80, width: 100}
            ,{field: 'artInfo',title: '入库时间',sort: true,templet: '<div>{{d.artInfo.addTime}}</div>'}
            ,{title: '操作', width: 180, align:'center', fixed: 'right', toolbar: '#table-operation'}
        ]]
        ,page: true
        ,limit: 10
        ,height: 'full-80'
        ,text: '对不起，加载出现异常！'
    });


    /* 艺术品类别 */

    $.ajax({
        url : configs.base_server + "/art/artType/list",
        type:'get',
        data:{},
        success:function (data) {

            var $html = "";
            if(data.artTypeList != null){
                $.each(data.artTypeList, function (index, item) {
                        $html += "<option value='" + item.artTypeId + "'>" + item.artTypeName + "</option>";
                });
                $("select[name='artTypeId']").append($html);

                //append后必须从新渲染
                form.render('select');
            }
        }
    })


    //监听搜索
    form.on('submit(lay-submit-search)', function(data){
        var field = data.field;

        //执行重载
        table.reload('lay-tab', {
            where: field
        });
    });

    // 上下架状态修改
    form.on('switch(status_filter)',function (obj) {

        var field = {};
        field.userId = obj.elem.value;
        field.status = obj.elem.checked ? 1 : 0;

        if(field.userId == 1){
            layer.msg("管理员不能禁用",{icon: 2});
            table.reload('lay-tab');
        }else{

            admin.req({
                url : "../../sys/user/update",
                type : "post",
                contentType: "application/json",
                data: JSON.stringify(field),
                success:function (data) {
                    console.log(data);
                    if(data.code == 0){
                        layer.msg("操作成功",{icon: 1});
                    }else{
                        layer.msg("操作失败",{icon: 2});
                    }
                }
            });

        }


    });

    //事件
    var active = {
        del: function(){
            var checkStatus = table.checkStatus('lay-tab')
                ,checkData = checkStatus.data //得到选中的数据
                ,userIds= [];   //  定义空数组 用来存放 多个id   var userId = new Array();
            for (var index in checkData){
                console.log(checkData[index].userId);
                userIds.push(checkData[index].userId)
            }
            var  aa = JSON.stringify(userIds);

            if(checkData.length === 0){
                return layer.msg('请选择数据');
            }
            layer.confirm('确定删除吗？', function() {

                $.ajax({
                    type: "POST",
                    url : "../../sys/user/delete",
                    contentType: "application/json",
                    data: JSON.stringify(userIds),
                    success: function(data){
                        if(data.code == 0){
                            layer.msg("删除成功",{icon: 1});

                        }else{
                            layer.msg(data.msg,{icon: 2});
                        }
                        table.reload('lay-tab');
                    }
                });

            });
        }
        ,add: function(){
            layer.open({
                type: 2
                ,title: '艺术品入库申请'
                ,content: 'icdnform.html'
                ,maxmin: true
                ,area: ['800px', '450px']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'lay-bth-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){

                        var field = data.field; //获取提交的字段

                        console.log(field);
                        //提交 Ajax 成功后，静态更新表格中的数据
                        $.ajax({
                            url : configs.base_server + "art/artInfo/save"
                            ,type : 'post'
                            ,data : field
                            ,success :function (data) {
                                if(data.code == 0){
                                    layer.msg("添加成功",{icon: 1});

                                }else{
                                    layer.msg(data.msg,{icon: 2});
                                }
                                table.reload('lay-tab');
                            }
                        });
                        layer.close(index); //关闭弹层
                    });
                    submit.trigger('click');
                }
            });
        }
    };

    $('.layui-btn.ud-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    //监听工具条
    table.on('tool(lay-tab)', function(obj){
        var data = obj.data;
        if(obj.event === 'add'){

            layer.open({
                type: 2
                ,title: '申请采集信息'
                ,content: 'applycoll.html'
                ,maxmin: true
                ,area: ['800px', '450px']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'lay-bth-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        var field = data.field;
                        field.userId = obj.data.userId;
                        var status;
                        if('switch' in field){  // 包含该元素
                            status = 1 ;
                        }else{
                            status = 0;
                        }
                        field.status = status;
                        console.log(field);
                        // 修改
                        $.ajax({
                            type: "POST",
                            url : "../../sys/user/update",
                            contentType: "application/json",
                            data: JSON.stringify(field),
                            success: function(data){
                                if(data.code == 0){
                                    layer.msg("修改成功",{icon: 1});

                                }else{
                                    layer.msg(data.msg,{icon: 2});
                                }
                                table.reload('lay-tab');
                            }
                        });
                        layer.close(index); //关闭弹层
                    });

                    submit.trigger('click');
                }
                ,success: function(layero, index){

                    var div = layero.find('iframe').contents().find('#lay-form');

                    var icdnInfodata = obj.data;

                    div.find('#artName').val(icdnInfodata.artInfo.artName);
                    div.find('#artTypeName').val(icdnInfodata.artType.artTypeName);
                    div.find('#artMaterial').val(icdnInfodata.artInfo.artMaterial);
                    div.find('#size').val(icdnInfodata.artInfo.artNormsLong+";"+icdnInfodata.artInfo.artNormsWide+";"+icdnInfodata.artInfo.artNormsHeight);

                    var image_url = icdnInfodata.artImage.imageUrl;

                    var strs = new Array(); //定义一数组
                    strs = image_url.split(";"); //字符分割
                    var image,$html ="";
                    for (i = 0; i < strs.length; i++) {
                        image = strs[i];
                        $html += "<img src=" + image + " style='width:150px;height:150px;margin-right:3px;' class='img-rounded'/>";
                    }

                    console.log($html);
                    div.find('#img').append($html);

                }
            });

        } else if(obj.event === 'details'){

            layer.open({
                type: 2
                ,title: '查看详情'
                ,content: 'icdndetail.html'
                ,maxmin: true
                ,area: ['800px', '450px']
                ,btn: ['确定', '取消']
                ,success: function(layero, index){

                    var div = layero.find('iframe').contents().find('#lay-form');

                    var icdnInfodata = obj.data;

                    div.find('#artName').val(icdnInfodata.artInfo.artName);
                    div.find('#artTypeName').val(icdnInfodata.artType.artTypeName);
                    div.find('#artMaterial').val(icdnInfodata.artInfo.artMaterial);
                    div.find('#size').val(icdnInfodata.artInfo.artNormsLong+";"+icdnInfodata.artInfo.artNormsWide+";"+icdnInfodata.artInfo.artNormsHeight);
                    if(icdnInfodata.artScanInfo != null){
                        div.find('#hyperspectral').val(icdnInfodata.artScanInfo.hyperspectral !=null? icdnInfodata.artScanInfo.hyperspectral : "暂无数据");
                        div.find('#highPrecision').val(icdnInfodata.artScanInfo.highPrecision !=null? icdnInfodata.artScanInfo.highPrecision : "暂无数据");
                        div.find('#trueColor').val(icdnInfodata.artScanInfo.trueColor !=null? icdnInfodata.artScanInfo.trueColor : "暂无数据");
                    }else {
                        div.find('#hyperspectral').val("暂无数据");
                        div.find('#highPrecision').val("暂无数据");
                        div.find('#trueColor').val("暂无数据");
                    }

                    var image_url = icdnInfodata.artImage.imageUrl;

                    var strs = new Array(); //定义一数组
                    strs = image_url.split(";"); //字符分割
                    var image,$html ="";
                    for (i = 0; i < strs.length; i++) {
                        image = strs[i];
                        $html += "<img src=" + image + " style='width:150px;height:150px;margin-right:3px;' class='img-rounded'/>";
                    }

                    console.log($html);
                    div.find('#img').append($html);

                }
            });
        }
    });


    var imgListView = $("#imgList"),
        uploadListIns =  upload.render({
            elem: '#uploadImg'
            ,url: configs.base_server + 'pic/upload/'
            ,auto: false
            ,multiple: true
            ,bindAction: '#uploadBtn'
            // ,before: function(obj){
            ,choose: function(obj){
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td width="100px">'+ file.name +'</td>'
                        ,'<td><img src="'+ result +'" alt="'+ file.name +'" style="width: 150px;height: 150px;"></td>'
                        ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                        ,'<td>等待上传</td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    imgListView.append(tr);
                    $('.imageTab').removeClass('layui-hide');
                });
            }
            ,done: function(res, index, upload){

                if(res.code == 0){ //上传成功
                    // 拼接图片的 url
                    var img_url =  $("#image_url").val();
                    img_url += res.url+";";
                    $("#image_url").val(img_url);
                    $("#cover_image_url").val(res.url);

                    var tr = imgListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(4).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            ,error: function(index, upload){
                var tr = imgListView.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });






    exports('icdnlist', {})
});